# -*- coding: utf-8 -*-

import os
import sys
import datetime
import pytz
import jinja2

from openerp import SUPERUSER_ID, models
from openerp.osv import fields
from openerp.osv import orm
from openerp.osv import osv

if hasattr(sys, 'frozen'):
    # When running on compiled windows binary, we don't have access to package loader.
    path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'views'))
    loader = jinja2.FileSystemLoader(path)
else:
    loader = jinja2.PackageLoader('openerp.addons.hfsy_lodop', "report")

env = jinja2.Environment(loader=loader, autoescape=True)

#jinja2模版自定义过滤器
def strftime(str, fmt):
    dt = datetime.datetime.strptime(str, '%Y-%m-%d %H:%M:%S')
    dt = dt.replace(tzinfo=pytz.utc).astimezone(pytz.timezone('Asia/Shanghai'))
    return dt.strftime(fmt.encode('utf-8')).decode('utf-8')

env.filters['strftime'] = strftime



# 销售订单打印扩展，调用lodop打印
class sale_order_lodop(osv.osv):
    _name = 'sale.order'
    _inherit = 'sale.order'

    def print_quotation(self, cr, uid, ids, context=None):
        '''
        This function prints the sales order and mark it as sent, so that we can see more easily the next step of the workflow
        '''
        assert len(ids) == 1, 'This option should only be used for a single id at a time'
        order = self.browse(cr, uid, ids, context=context)
        #if order.state == "progress":
        #    self.signal_workflow(cr, uid, ids, 'order_print')
        #else:
        #    self.signal_workflow(cr, uid, ids, 'quotation_sent')
        #会调用下面的sale_order_lodop_report方法(report/models/report.py 156行特殊报表:particularreport_obj，是关键)
        return self.pool['report'].get_action(cr, uid, ids, 'sale_order_lodop', context=context)



# render订单打印模板
class report_sale_order_lodop(osv.AbstractModel):
    """Model used to embed old style reports"""
    _name = 'report.sale_order_lodop'
    _template = None
    _wrapped_report_class = None

    def render_html(self, cr, uid, ids, data=None, context=None):
        model = 'sale.order'
        report_obj = self.pool[model]
        order = report_obj.browse(cr, uid, ids, context=context)
        #如果订单不是草稿状态或待审核状态打印，则将打印状态修改为已打印
        if order.state not in ['draft', 'sent']:
            order.write({'print_state': True})
        note_lines = []
        if order.note:
            note_lines = order.note.split('\n')
        options = data or {}
        template = env.get_template("sale_order_print.html")
        return template.render({
            'order': order,
            'note_lines': note_lines,
            'debug': context,
            'options': options,
            })
        #return self.pool['report'].render(cr, uid, [], self._template, docargs, context=context)

# render出货单打印模板
class report_stock_picking_lodop(osv.AbstractModel):
    """Model used to embed lodop reports"""
    _name = 'report.stock_report_picking_ext'
    _template = None
    _wrapped_report_class = None

    def render_html(self, cr, uid, ids, data=None, context=None):
        model = 'stock.picking'
        report_obj = self.pool[model]
        picking = report_obj.browse(cr, uid, ids, context=context)
        is_printed = picking.is_printed
        if not is_printed:
            picking.write({'is_printed': True})

        #先取到出货单对应的订单id，再去取得订单的对象
        order_id = self.pool.get('sale.order').search(cr, uid, [('name','=',picking.origin)])
        order = self.pool.get('sale.order').browse(cr, uid, order_id, context=None)
        curUser = self.pool.get('res.users').browse(cr,uid,uid,context=None)
        template = env.get_template("stock_picking_print.html")
        return template.render({
            'picking': picking,
            'order': order,
            'curUser': curUser,
            'debug': context,
            'is_printed': is_printed,
            })
